<template>
    <div class="code-edit">
        <el-card class="!border-none" shadow="never">
            <el-page-header content="编辑公告" @back="$router.back()" />
        </el-card>
        <el-card class="mt-4 !border-none" shadow="never">
            <!-- <el-form ref="formRef" class="ls-form" :model="table_column" label-width="100px" :rules="rules"> -->
            <el-form class="ls-form" ref="formRef" :rules="rules" :model="formData" label-width="60px">
                <el-form-item label="标题" prop="name">
                    <el-input class="ls-input" v-model="formData.name" placeholder="请输入名称" clearable />
                </el-form-item>
                <el-form-item label="附件" prop="desc">
                    <el-upload v-model:file-list="formData.fileList" ref="upload" class="upload-demo" :action="action"
                        :show-file-list="true" :headers="headers" :on-exceed="handleExceed" :on-success="handleSuccess"
                        :on-error="handleError">
                        <el-button type="primary">本地上传</el-button>
                    </el-upload>
                    <!-- <upload class="mr-3" type="file" :show-progress="true" @change="handleExceed">
                        <el-button type="primary">本地上传</el-button>
                    </upload> -->
                </el-form-item>
                <el-form-item label="介绍" prop="content">
                    <editor v-model="formData.description" :height="567" :width="775" />
                </el-form-item>
                <!-- <el-form-item label="介绍" prop="sort">
                    <el-input-number v-model="formData.sort" :min="0" :max="9999" />
                </el-form-item> -->
            </el-form>
            <!-- </el-form> -->
        </el-card>
        <footer-btns>
            <el-button type="primary" @click="onSubmit">保存</el-button>
        </footer-btns>
    </div>
</template>

<script lang="ts" setup name="tableEdit">
import type { FormInstance } from 'element-plus'
import { cloneDeep } from 'lodash'

import config from '@/config'

// import upload from "@/components/upload/index.vue"

import { menuAll } from '@/api/perms/menu'
import { roleInfor } from '@/api/perms/role'

import { dictTypeAll } from '@/api/setting/dict'
import { noticeEdit, noticeDetail, noticeAdd } from '@/api/notice/notice'
import { useDictOptions } from '@/hooks/useDictOptions'
import feedback from '@/utils/feedback'
import useMultipleTabs from '@/hooks/useMultipleTabs'
const { removeTab } = useMultipleTabs()

import useAppStore from '@/stores/modules/app'
import useUserStore from '@/stores/modules/user'

import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
const upload = ref<UploadInstance>()

// import RelationsAdd from '../components/relations-add.vue'
const userStore = useUserStore()
const appStore = useAppStore()
const action = ref(`${config.baseUrl}${config.urlPrefix}/upload/file`)
console.log(action.value, "action")
const headers = computed(() => ({
    token: userStore.token,
    version: appStore.config.version
}))

console.log("record")
const route = useRoute()
const router = useRouter()
const activeName = ref('column')
const showEdit = ref(false)
const relationTypes = [
    {
        name: '一对一',
        value: 'has_one'
    },
    {
        name: '一对多',
        value: 'has_many'
    }
]
const table_column = ref([])

const formData = reactive({
    id: '',
    name: '',
    description: '',
    file_id: '',
    file: {},
    fileList: []
})
let editIndex = 0
const formRef = shallowRef<FormInstance>()
// const editRef = shallowRef<InstanceType<typeof RelationsAdd>>()
const rules = reactive({
    table_name: [{ required: true, message: '请输入表名称' }],
    table_comment: [{ required: true, message: '请输入表描述' }],
    module_name: [{ required: true, message: '请输入模块名' }],
    generate_type: [{ required: true, trigger: 'change' }],
    template_type: [{ required: true, trigger: 'change' }],
    ['menu.pid']: [{ required: true, message: '请选择父级菜单' }],
    ['menu.name']: [{ required: true, message: '请输入菜单名称' }],
    ['delete.type']: [{ required: true, trigger: 'change' }],
    ['delete.name']: [{ required: true, message: '请选择删除字段' }]
})

const showEditPopup = async (type: string, data?: any, index?: number) => {
    showEdit.value = true
    await nextTick()
    if (data && index !== undefined) {
        // editRef.value?.setFormData(data)
        editIndex = index
    }
    // editRef.value?.open(type)
}

const handleAdd = (data: any) => {
    const newData = cloneDeep(toRaw(data))
    formData.relations.push(newData)
}
const refresh = async (data: any) => {
    console.log(data, "dataUrl")
    // const newData = cloneDeep(toRaw(data))
    // console.log(editIndex)
    // formData.relations.splice(editIndex, 1, newData)
}
const handleEdit = async (data: any) => {
    const newData = cloneDeep(toRaw(data))
    console.log(editIndex)
    formData.relations.splice(editIndex, 1, newData)
}

const handleExceed: UploadProps['onExceed'] = (files) => {

    upload.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    upload.value!.handleStart(file)
}


const handleSuccess = (event: any, file: any) => {
    console.log(event, file, "handleSuccess")
    if (event.show == 1) {
        feedback.msgError(`${file.name}文件上传失败`)
        formData['fileList'] = formData['fileList'].slice(0, 1)
    } else {
        formData.fileList[0] = {
            id: event.data.id,
            name: event.data.name,
            uri: event.data.uri,
            url: event.data.url,
        }
        formData.file_id = event.data.id
        formData['fileList'] = formData['fileList'].slice(0, 1)
        formData['file'] = formData.fileList[0]
    }
}
const handleError = (event: any, file: any) => {
    console.log(event, file, "handleError")
    // feedback.msgError(`${file.name}文件上传失败`)
}

const handelDelete = (index: number) => {
    formData.relations.splice(index, 1)
}
const getDetails = async () => {
    const data = await noticeDetail({
        id: route.query.id
    })
    // formData = data
    Object.keys(formData).forEach((key) => {
        //@ts-ignore
        formData[key] = data[key]
    })
    formData['fileList'] = [formData['file']]
    console.log(formData, "formData")
    // watch(
    //     () => formData.generate_type,
    //     (value) => {
    //         if (value == 1) {
    //             feedback
    //                 .confirm('生成到模块方式如遇同名文件会覆盖旧文件，确定要选择此方式吗？')
    //                 .catch(() => {
    //                     formData.generate_type = 0
    //                 })
    //         }
    //     }
    // )

}

const boxAdmin = (index: any) => {
    console.log(index, "index")
}

const getlists = async () => {
    table_column.value = await roleInfor()
    // console.log(data, "data")
    // Object.keys(formData).forEach((key) => {
    //     //@ts-ignore
    //     formData[key] = data[key]
    // })

    // watch(
    //     () => formData.generate_type,
    //     (value) => {
    //         if (value == 1) {
    //             feedback
    //                 .confirm('生成到模块方式如遇同名文件会覆盖旧文件，确定要选择此方式吗？')
    //                 .catch(() => {
    //                     formData.generate_type = 0
    //                 })
    //         }
    //     }
    // )
}
const { optionsData } = useDictOptions<{
    dict_type: any[]
    menu: any[]
}>({
    dict_type: {
        api: dictTypeAll
    },
    menu: {
        api: menuAll,
        transformData(data) {
            const menu = { id: 0, name: '顶级', children: [] }
            menu.children = data
            return [menu]
        }
    }
})

const onSubmit = async () => {

    console.log(formData, "table_column")

    try {
        if (route.query.id) {
            await noticeEdit(formData)
        } else {
            await noticeAdd(formData)
        }
        removeTab()
        router.back()
    } catch (error: any) {
        for (const err in error) {
            const isInRules = Object.keys(rules).includes(err)
            isInRules && feedback.msgError(error[err][0]?.message)
        }
    }
}
if (route.query.id) {
    getDetails()
}
// getlists()
</script>
